<script lang="ts" setup>
import { addBanner, deleteBanner, getBanner, getBannerList, upBanner } from "@/api/marketers/banner/banner";
import { getProduct } from "@/api/marketers/product";
import { ElMessage, type FormInstance, type UploadProps } from "element-plus";
import { reactive, ref, toRefs } from "vue";
const bannerList = ref<Banner[]>([]);
const loading =ref(false)
const dialogVisible = ref(false);
const dialogtitle = ref("");
const formRef = ref();
const isSumbit =ref(false)
const productList =ref()
interface Banner {
  bannerId: number;
  bannerName: string;
  productId: number;
  productName: string;
  bannerImg: string;
  sort: number;
}
const bannerNameRule = (rule: any, value: any, callback: any) => {

if (!value.trim() ||value.trim() === '') {
    callback(new Error('商品名称不能为空'))
} else if (value.trim().length < 1 || value.trim().length > 20) {
    callback(new Error('长度为1到20位'))
} else {
    callback()
}
}
const bannerimgRule = (rule: any, value: any, callback: any) => {
if(value === undefined){
  callback(new Error("至少有一张图片"))
}
else if (value[0] == null || value[0] == undefined || value === undefined) {
    callback(new Error("至少有一张图片"))
}else {
    callback()
}
}
const data = reactive({
  form: <Banner>{
    bannerName:'',

    sort:0,
    bannerImg:''
  },
  queryParams: {},
  rules: {
    bannerName: [
        { required: true, validator: bannerNameRule, trigger: 'blur' }
    ],
    price: [
        { required: true, message: '必须设置价格' },
        { type: 'number', message: '只能是阿拉伯数字' },
    ],
    bannerImg: [
        { required: true, validator: bannerimgRule, trigger: 'blur' }
    ]
}
});
const { form, queryParams, rules } = toRefs(data);
//初始化
async function load() {
  loading.value=true
  await getBannerList(queryParams.value).then((response) => {
    bannerList.value = response.data.rows;
  });
  loading.value=false
}
// 新增按钮
const addButton = () => {
  isSumbit.value =true
  dialogVisible.value = true;
  dialogtitle.value = "新增轮播图";
};
// 修改按钮
const upButton = async (row:any) => {
  isSumbit.value =false
  dialogVisible.value = true;
  dialogtitle.value = "修改轮播图";
  await getBanner(row.bannerId).then(response=>{
      form.value = response.data.data
  })
};
//删除按钮
const deleteButton =async (row:any)=>{
  await deleteBanner([row.bannerId])
  load()
}
// 轮播图上传成功回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (response, uploadFile) => {
  form.value.bannerImg = response.data;
};
// 轮播图上传规则
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type !== "image/jpeg" &&
    rawFile.type !== "image/png" &&
    rawFile.type !== "image/gif"
  ) {
    ElMessage.error("轮播图必须是jpeg | png | gif");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("最大10MB!");
    return false;
  }
  return true;
};
//表单提交

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (isSumbit.value) {
        await addBanner(form.value)
      } else {
        await upBanner(form.value)
      }
      dialogVisible.value = false;
      load();
    }
  });
};
// 表单重置
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
//获取所有商品信息
async function getProductList(){
  await getProduct({}).then(response=>{
   productList.value= response.data.rows
  })
}
getProductList()
load();
</script>
<template>
  <!-- 查询 -->
  <!-- <el-from></el-from> -->
  <el-button type="primary" @click="addButton">新增</el-button>
  <el-divider />
  <el-table v-loading="loading" :data="bannerList">
    <el-table-column prop="bannerId" label="轮播图ID" width="100" />
    <el-table-column prop="bannerName" label="轮播图名称" width="150" />
    <el-table-column prop="productId" label="商品Id" width="100" />
    <el-table-column prop="productName" label="商品名称" width="150" />
    <el-table-column prop="bannerImg" label="图片">
      <template #default="scope">
        <el-image
          style="width: 200px; height: 100px"
          :src="scope.row.bannerImg"
          fit="cover"
        />
      </template>
    </el-table-column>
    <el-table-column prop="sort" label="排序" width="100" />
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column prop="updateTime" label="修改时间" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-button link @click="upButton(scope.row)" type="primary">修改</el-button>
        <el-popconfirm title="确定要删除吗？" @confirm="deleteButton(scope.row)">
          <template #reference>
            <el-button link type="primary">删除</el-button>
          </template>
        </el-popconfirm>
      </template>
    </el-table-column>
  </el-table>
  <!-- 新增-修改 -->
  <el-dialog
    v-model="dialogVisible"
    style="max-width: 600px"
    :title="dialogtitle"
    width="800"
    @close="resetForm(formRef)"
  >
    <el-form
      :model="form"
      :rules="rules"
      ref="formRef"
      label-width="auto"
      label-position="top"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item prop="bannerName" label="轮播名称">
            <el-input v-model="form.bannerName" style="width: 240px"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关联商品">
            <el-select
              v-model="form.productId"
              filterable
              placeholder="选择关联商品"
              style="width: 240px"
            >
              <el-option
                v-for="item in productList"
                :key="item.productId"
                :label="item.name"
                :value="item.productId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item prop="sort" label="排序">
            <el-input-number v-model="form.sort" controls-position="right" :min="0" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item prop="bannerImg" label="轮播图">
            <el-upload
              class="avatar-uploader"
              action="/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="form.bannerImg" :src="form.bannerImg" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item>
            <el-button type="primary" @click="submitForm(formRef)">确定</el-button>
            <el-button @click="dialogVisible = false">取消</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </el-dialog>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

<style scoped>
.avatar-uploader .avatar {
  width: 100%;
  height: 178px;
  display: block;
}
</style>
